package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl.task;

import com.alibaba.fastjson.JSON;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.TaskCreatedPostProcessor;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.UserService;
import com.iwhalecloud.citybrain.flow.platform.manager.application.utils.ParseRenderedVariable;
import com.iwhalecloud.citybrain.flow.platform.manager.application.utils.StringUtils;
import com.iwhalecloud.citybrain.flow.platform.manager.common.ConstanceVariable;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.enums.HandleStatusEnum;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.enums.HandleTypeEnum;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.*;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.app.FlowApp;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.form.FormProcessInstanceHandleRelDto;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.userentity.UserInfo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
@Order(30)
public class SaveReadDoInfoProcessor implements TaskCreatedPostProcessor {

    @Autowired
    private FlowNodeReaderRepository flowNodeReaderRepository;
    @Autowired
    private  FlowProcessInstanceHandleRelRepository flowProcessInstanceHandleRelRepository;

    @Autowired
    private FlowReModelCustomConfigRepository flowReModelCustomConfigRepository;

    @Autowired
    private FlowFormRepository flowFormRepository;

    @Autowired
    private FlowAppRepository flowAppRepository;

    @Autowired
    private UserService userService;

    /**
     * 阅办任务跳转地址
     */
    @Value("${task.readDoJumpUrl:http://flow-platform-web-daily.ingress.dayu.work/todo/templatepage?actype=todo&processInstanceId=:processInstanceId&taskId=:taskId}")
    private String readDoJumpUrl;

    /**
     * 任务来源应用编码
     */
    @Value("${task.sourceAppCode:mes2}")
    private String sourceAppCode;

    @Override
    public void process(TaskEntity taskEntity) {
        try {
            //1,查询要生成阅办的信息
            List<FlowNodeReaderVo> fnrs  = flowNodeReaderRepository.select(taskEntity.getProcessInstanceId(), taskEntity.getTaskDefinitionKey());
            if(CollectionUtils.isNotEmpty(fnrs)){
                for(FlowNodeReaderVo fnr : fnrs){
                    //2,生成阅办记录
                    List<FormProcessInstanceHandleRelDto> handleRelDtoList = new ArrayList<>();
                    FormProcessInstanceHandleRelDto fpihr = new FormProcessInstanceHandleRelDto();
                    fpihr.setHandlerId(fnr.getHandlerId());
                    fpihr.setHandleType(HandleTypeEnum.READTASK.getCode());
                    fpihr.setProcessInstanceId(fnr.getProcessInstanceId());
                    fpihr.setTaskId(taskEntity.getId());
                    fpihr.setSendUserCode(fnr.getSendUserCode());
                    // 根据userId查询人员信息,转换成用户名称
                    UserInfo userInfo = userService.getUserInfoObj(fnr.getSendUserCode());
                    fpihr.setSendUserName(userInfo == null? "" : userInfo.getUserName());
                    fpihr.setShouldCompleteTime(fnr.getShouldCompleteTime());
                    fpihr.setStatus(HandleStatusEnum.NOREAD.getCode().intValue());

                    // 为空时取默认
                    String defaultUrl = readDoJumpUrl.replace(":processInstanceId", taskEntity.getProcessInstanceId()).replace(":taskId", taskEntity.getId());

                    // 获取对接门户跳转到阅办的链接
                    String url = this.getJumpUrl(taskEntity);

                    // 外置表单跳转链接是空就取默认配置
                    String jumpConnection = url == null?defaultUrl:url;

                    // 获取用户任务外置表单跳转url,新增时多拼接一个状态,默认状态是未读
                    fpihr.setJumpUrl(jumpConnection+"&status="+ HandleStatusEnum.NOREAD.getCode().intValue() +"");

                    // 设置来源应用编码
                    fpihr.setSourceAppCode(sourceAppCode);

                    // 需要根据流程实例ID获取对应配置业务appCode传给待办组件查询区分业务使用
                    List<FlowApp> flowApps = flowAppRepository.getAppInfoByProcessInstanceId(taskEntity.getProcessInstanceId());
                    if(CollectionUtils.isNotEmpty(flowApps)) {
                        FlowApp flowApp = flowApps.get(0);
                        // 设置来源业务编码
                        fpihr.setBusinessCode(flowApp.getAppCode());
                    }

                    // 业务模块编码(业务侧发起传的)
                    String businessModuleCodeVar = taskEntity.getVariable(ConstanceVariable.BUSINESS_MODULE_CODE, String.class);
                    if(StringUtils.isNotBlank(businessModuleCodeVar)) {
                        fpihr.setBusinessModuleCode(businessModuleCodeVar);
                    }

                    // 表单模块编码(业务侧发起传的)
                    String formModuleCodeVar = taskEntity.getVariable(ConstanceVariable.FORM_MODULE_CODE, String.class);
                    if(StringUtils.isNotBlank(formModuleCodeVar)) {
                        fpihr.setFormModuleCode(formModuleCodeVar);
                    }

                    // 添加到数据集合中
                    handleRelDtoList.add(fpihr);
                    flowProcessInstanceHandleRelRepository.batchInsertFlowFormProcessInstanceHandleRel(handleRelDtoList);
                    //3，更新阅办信息为已处理
                    flowNodeReaderRepository.update(fnr.getId(), taskEntity.getTaskDefinitionKey());
                }
            }
        } catch (Exception ex) {
            log.error("生成阅办记录失败:" + ex.getMessage());
        }
    }

    /**
     * 获取跳转链接
     *
     * @param taskEntity
     * @return
     */
    private String getJumpUrl(TaskEntity taskEntity) {
        String url = null;
        String deployId = String.valueOf(taskEntity.getVariable(ConstanceVariable.DEPLOYMENT_ID));
        List<ModelCustomConfigDomain> modelCustomConfigDomainList = flowReModelCustomConfigRepository.listModelConfigByDeployIdAndType(deployId
                ,taskEntity.getTaskDefinitionKey(), ConstanceVariable.EXTERNAL_FORM_SHOW_STYLE);
        if (Objects.isNull(modelCustomConfigDomainList) || modelCustomConfigDomainList.isEmpty()){
            return url;
        }
        String showType = modelCustomConfigDomainList.get(0).getConfig();
        if (Objects.equals(showType,"empty")){
            String formkey = taskEntity.getFormKey();
            FlowFormExternalInfoDomain flowFormExternalInfoDomain = flowFormRepository.findExternalFormInfo(formkey);
            if (Objects.nonNull(flowFormExternalInfoDomain)){
                String formUrl = flowFormExternalInfoDomain.getFormUrl();
                url = ParseRenderedVariable.parseRenderedVariable(formUrl,taskEntity);
                log.error("getTaskExternalUrlForTodoComp->url="+url);
                return url;
            }
        }
        return url;
    }

}
